<?php
declare(strict_types=1);

namespace App\Common\Query;

use Hyperf\Database\Model\Builder;
use Zms\Unit\Time;

class Query
{
    /**
     * 名称搜索器
     * @param Builder $query
     * @param $key
     * @param $keyword
     */
    public static function LikeSearch(Builder $query, $key, $keyword): void
    {
        if (is_string($keyword) && strlen($keyword) > 0) {
            $query->where($key, 'LIKE', "%$keyword%");
        }
    }


    /**
     * 名称搜索器
     * @param Builder $query
     * @param $key
     * @param $keyword
     */
    public static function IpSearch(Builder $query, $key, $keyword): void
    {
        if (is_string($keyword) && strlen($keyword) > 0) {
            $query->where([$key => inet_pton($keyword)]);
        }
    }


    /**
     * 相等或IN搜索
     * @param Builder $query
     * @param $key
     * @param $value
     * @return void
     */
    public static function EqualOrInSearch(Builder $query, $key, $value): void
    {
        if (is_array($value) && count($value) > 0) {
            $query->whereIn($key, $value);
        } else {
            $query->where($key, $value);
        }
    }


    /**
     * 日期范围搜索
     * @param Builder $query
     * @param $key
     * @param $time
     * @return void
     */
    public static function TimeRangeSearch(Builder $query, $key, $time): void
    {
        if (is_array($time)) {
            if (isset($time[0]) && $time[0]) {
                if (is_numeric($time[0])) {
                    $query->whereRaw("({$key}>=?)", [Time::value($time[0])]);
                } elseif (strlen($time[0]) === 10) {
                    $query->whereRaw("({$key}>=?)", [Time::value($time[0] . ' 00:00:00')]);
                } else {
                    $query->whereRaw("({$key}>=?)", [Time::value($time[0])]);
                }
            }
            if (isset($time[1]) && $time[1]) {
                if (is_numeric($time[0])) {
                    $query->whereRaw("({$key}<?)", [Time::value($time[1])]);
                } elseif (strlen($time[0]) === 10) {
                    $query->whereRaw("({$key}<?)", [Time::value($time[1] . ' 23:59:59')]);
                } else {
                    $query->whereRaw("({$key}<?)", [Time::value($time[1])]);
                }
            }
        }
    }

    /**
     * 点链接查询
     * @param Builder $query
     * @param $key
     * @param int|string|array $value
     * @return void
     */
    public static function FindInSetSearch(Builder $query, $key, int|string|array $value): void
    {
        if (is_array($value)) {
            $skwhere = [];
            $bind = [];
            foreach ($value as $val) {
                $skwhere[] = "FIND_IN_SET(?,{$key})";
                $bind[] = $val;
            }
            $query->whereRaw('(' . implode(' OR ', $skwhere) . ')', $bind);
        } else {
            $query->whereRaw("FIND_IN_SET(?,{$key})", [$value]);
        }
    }
}